﻿using DeHeng_Mes.Dao;
using DeHeng_Mes.Model;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace DeHeng_Mes.Thread
{
    public class Andon
    {
        Dictionary<string, string> andonConfig = AndonConfigModelDic.AndonModel;
        AndonDao andonDao = new AndonDao();
        /// <summary>
        /// 初始化安灯报警缓存
        /// </summary>
        /// <returns></returns>
        public void AndonInit(bool isCollect)
        {
            if (isCollect)
            {
                // 查询数据库中缓存的安灯报警信息
                List<Model.Table.AndonVoice> andonVoices = andonDao.GetAndon();

                // 添加到缓存中
                if (andonVoices != null && andonVoices.Count > 0)
                {
                    foreach (var andonVoice in andonVoices)
                    {
                        andonConfig.Add(andonVoice.AndonId, andonVoice.Voice);
                    }
                    Tools.ProduceLogText($"添加了{andonVoices.Count}条数据进入安灯缓存模型");
                }
                else
                {
                    Tools.ProduceLogText($"未发现未完成的安灯数据");
                }
            }
            else
            {
                Tools.ProduceLogTextError($"数据库未连接，无法进行安灯数据查询");
            }
        }

        /// <summary>
        /// 播放安灯文本
        /// </summary>
        /// <returns></returns>
        public async void AndonPlay()
        {
            while (true)
            {
                try
                {
                    if (andonConfig != null && andonConfig.Count > 0)
                    {
                        AndonSpeechSynthesizer.SpeechSynthesizer.Rate = -2;
                        foreach (var andonText in andonConfig)
                        {
                            AndonSpeechSynthesizer.SpeechSynthesizer.Speak(andonText.Value);
                            await Task.Delay(500);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogText(ex.Message);
                }
                await Task.Delay(3000);
            }
        }
    }
}
